import paho.mqtt.client as mqtt


# 方法1: 用户认证 + ssl/tls加密
def mqtt_init():
    client = mqtt.Client()
    client.username_pw_set("username", "password")
    client.tls_set(ca_certs="ca.crt")  # 设置 CA 证书
    client.connect("127.0.0.1", 8883, 60)


# 方法2: 配置文件形式: 用户认证 + ssl/tls加密
Config = {
    "mqtt_broker": {
        "ip": "127.0.0.1",
        "port": 1883,
        "username": "",
        "password": "",
        "ca_file": "",
    },
}
def mqtt_init_config(config):
    ip = config["mqtt_broker"]["ip"]
    port = config["mqtt_broker"]["port"]
    # 连接mqtt服务器
    client = mqtt.Client()
    client.connect(ip, port, 60)

    # 用户认证
    username = config["mqtt_broker"]["username"]
    password = config["mqtt_broker"]["password"]
    if username and password:
        client.username_pw_set(username, username)

    # ssl/tls认证
    ca_file = config["mqtt_broker"]["ca_file"]
    if ca_file:
        client.tls_set(ca_certs=ca_file)
